<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>账单统计系统</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <script src="/static/js/vue.global.prod.min.js"></script>
    <script src="/static/js/chart.umd.min.js"></script>
    <script src="/static/js/axios.min.js"></script>
    <style>
        .stat-card {
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .chart-container {
            height: 300px;
            position: relative;
        }

        .fade-enter-active,
        .fade-leave-active {
            transition: opacity 0.5s;
        }

        .fade-enter,
        .fade-leave-to {
            opacity: 0;
        }
    </style>
</head>

<body>
    <div id="app" class="container py-4">
        <h1 class="text-center mb-4">账单统计系统</h1>

        <!-- 时间筛选 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <select v-model="period" @change="loadData" class="form-select">
                    <option value="day">按日统计</option>
                    <option value="month">按月统计</option>
                    <option value="year">按年统计</option>
                </select>
            </div>
            <div class="col-md-4" v-if="period === 'day'">
                <input type="date" v-model="date" @change="loadData" class="form-control">
            </div>
            <div class="col-md-4" v-if="period === 'month'">
                <select v-model="month" @change="loadData" class="form-select">
                    <option v-for="m in months" :value="m">[[ m ]]</option>
                </select>
            </div>
            <div class="col-md-4" v-if="period === 'year'">
                <select v-model="year" @change="loadData" class="form-select">
                    <option v-for="y in years" :value="y">[[ y ]]</option>
                </select>
            </div>
        </div>

        <!-- 综合统计 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card stat-card bg-danger text-white">
                    <div class="card-body">
                        <h5 class="card-title">支出总额</h5>
                        <p class="card-text display-6">[[ formatCurrency(stats.expense) ]]</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title">收入总额</h5>
                        <p class="card-text display-6">[[ formatCurrency(stats.income) ]]</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card stat-card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title">结余总额</h5>
                        <p class="card-text display-6">[[ formatCurrency(stats.balance) ]]</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">支出</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="expenseChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">收入</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="incomeChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 趋势图（按月/年） -->
        <div class="row mb-4" v-if="period !== 'day'">
            <button class="btn btn-primary me-2" @click="toggleTrend('expense')">
                切换支出趋势图 (当前: [[ expenseTrendType === 'total' ? '总金额' : '分类' ]])
            </button>
            <div class="col-md-12" v-if="expenseTrendType=='category'">
                <div class="card">
                    <div class="card-header">[[ period === 'month' ? '每日支出趋势' : '每月支出趋势' ]]</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="expenseTrendChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12" v-if="expenseTrendType=='total'">
                <div class="card">
                    <div class="card-header">[[ period === 'month' ? '每日支出趋势' : '每月支出趋势' ]]</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="totalExpenseTrendChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <br>
            <button class="btn btn-primary me-2" @click="toggleTrend('income')">
                切换支出趋势图 (当前: [[ incomeTrendType === 'total' ? '总金额' : '分类' ]])
            </button>
            <div class="col-md-12" v-if="incomeTrendType=='category'">
                <div class="card">
                    <div class="card-header">[[ period === 'month' ? '每日收入趋势' : '每月收入趋势' ]]</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="incomeTrendChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12" v-if="incomeTrendType=='total'">
                <div class="card">
                    <div class="card-header">[[ period === 'month' ? '每日收入趋势' : '每月收入趋势' ]]</div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas ref="totalIncomeTrendChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 账单列表 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">账单明细</div>
                    <div class="card-body">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th width="200px">日期</th>
                                    <th width="120px">类型</th>
                                    <th width="120px">金额</th>
                                    <th width="120px">类别</th>
                                    <th width="120px">二级分类</th>
                                    <th width="120px">账户</th>
                                    <th>备注</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="bill in bills" :key="bill.id">
                                    <td>[[ bill.date ]]</td>
                                    <td
                                        :class="{'text-success': bill.type === '收入', 'text-danger': bill.type === '支出'}">
                                        [[ bill.type ]]
                                    </td>
                                    <td
                                        :class="{'text-success': bill.type === '收入', 'text-danger': bill.type === '支出'}">
                                        [[ formatCurrency(bill.amount) ]]
                                    </td>
                                    <td>[[ bill.category ]]</td>
                                    <td>[[ bill.subcategory ]]</td>
                                    <td>[[ bill.account ]]</td>
                                    <td>[[ bill.remark ]]</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted, watch, nextTick } = Vue;

        /* 配置Vue使用自定义分隔符 */
        const app = createApp({
            delimiters: ['[[', ']]'],
            setup() {
                const incomeChart = ref(null);
                const expenseChart = ref(null);
                const incomeTrendChart = ref(null);
                const expenseTrendChart = ref(null);
                const totalIncomeTrendChart = ref(null);
                const totalExpenseTrendChart = ref(null);

                const period = ref('day');
                const date = ref('');
                const month = ref('');
                const year = ref('');

                const stats = ref({
                    income: 0,
                    expense: 0,
                    balance: 0,
                    income_by_category: {},
                    expense_by_category: {},
                    income_by_subcategory: {},
                    expense_by_subcategory: {},
                    daily_stats: null
                });

                const bills = ref([]);
                const months = ref([]);
                const years = ref([]);

                let incomeChartInstance = null;
                let expenseChartInstance = null;
                let incomeTrendChartInstance = null;
                let expenseTrendChartInstance = null;
                let totalIncomeTrendChartInstance = null;
                let totalExpenseTrendChartInstance = null;

                // 初始化日期
                const initDates = async () => {
                    try {
                        // 获取最新账单日期
                        const response = await axios.get('/api/bills/stats?period=day');
                        if (response.data && response.data.date) {
                            date.value = response.data.date;
                        } else {
                            const today = new Date();
                            date.value = today.toISOString().split('T')[0];
                        }
                        const today = new Date();
                        month.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
                        year.value = today.getFullYear().toString();
                    } catch (error) {
                        console.error('获取最新日期失败:', error);
                        const today = new Date();
                        date.value = today.toISOString().split('T')[0];
                        month.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
                        year.value = today.getFullYear().toString();
                    }
                };
                // 在setup()函数中添加以下响应式变量
                const expenseTrendType = ref('total');
                const incomeTrendType = ref('total');

                // 在toggleTrend函数中完善逻辑
                const toggleTrend = (type) => {
                    if (type == 'expense') {
                        expenseTrendType.value = expenseTrendType.value == 'total' ? 'category' : 'total';
                        console.log('toggleTrend', expenseTrendType.value);
                    } else if (type == 'income') {
                        incomeTrendType.value = incomeTrendType.value == 'total' ? 'category' : 'total';
                    }
                    // 在状态改变后重新更新图表
                    nextTick(() => {
                        updateCharts();
                    });
                };


                // 加载数据
                const loadData = async () => {
                    let url = `/api/bills/stats?period=${period.value}`;

                    if (period.value === 'day') {
                        url += `&date=${date.value}`;
                    } else if (period.value === 'month') {
                        url += `&date=${month.value}-01`;
                    } else if (period.value === 'year') {
                        url += `&date=${year.value}-01-01`;
                    }

                    try {
                        const response = await axios.get(url);
                        stats.value = response.data;
                        bills.value = response.data.bills;

                        // 更新图表
                        updateCharts();
                    } catch (error) {
                        console.error('加载数据失败:', error);
                    }
                };

                // 格式化金额
                const formatCurrency = (value) => {
                    return value.toLocaleString('zh-CN', {
                        style: 'currency',
                        currency: 'CNY'
                    });
                }
                // 计算指定分类下的二级分类统计
                const calculateSubcategoryStats = (category) => {
                    const subcategoryStats = {};
                    let totalAmount = 0;

                    bills.value.forEach(bill => {
                        if (bill.type === '支出' && bill.category === category) {
                            if (!subcategoryStats[bill.subcategory]) {
                                subcategoryStats[bill.subcategory] = 0;
                            }
                            subcategoryStats[bill.subcategory] += bill.amount;
                            totalAmount += bill.amount;
                        }
                    });

                    return {
                        subcategoryStats,
                        totalAmount
                    };
                };

                // 显示二级分类统计模态框
                const showSubcategoryModal = (category) => {
                    const { subcategoryStats, totalAmount } = calculateSubcategoryStats(category);
                    if (null in subcategoryStats) {
                        showBillsModal(category, null);
                        return;
                    }

                    // 创建模态框DOM元素
                    const modal = document.createElement('div');
                    modal.className = 'modal fade show';
                    modal.style.display = 'block';
                    modal.innerHTML = `
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${category}支出统计</h5>
                        <button type="button" class="btn-close" onclick="this.parentNode.parentNode.parentNode.remove()"></button>
                    </div>
                    <div class="modal-body">
                        <div class="chart-container mb-4">
                            <canvas id="subcategoryChart"></canvas>
                        </div>
                        <div class="text-center">
                            <h4>总计: ${formatCurrency(totalAmount)}</h4>
                        </div>
                    </div>
                </div>
            </div>
        `;

                    // 添加到body
                    document.body.appendChild(modal);

                    // 创建子分类图表
                    nextTick(() => {
                        const canvas = modal.querySelector('#subcategoryChart');
                        if (canvas) {
                            const ctx = canvas.getContext('2d');
                            const labels = Object.keys(subcategoryStats);
                            const data = Object.values(subcategoryStats);

                            new Chart(ctx, {
                                type: 'pie',
                                data: {
                                    labels: labels,
                                    datasets: [{
                                        data: data,
                                        backgroundColor: [
                                            '#4BC0C0', '#36A2EB', '#FFCE56', '#FF6384', '#9966FF',
                                            '#FF9F40', '#8AC24A', '#607D8B', '#E91E63', '#9C27B0'
                                        ]
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        title: {
                                            display: true,
                                            text: `${category}支出分类分布`,
                                            position: 'bottom',
                                            font: {
                                                size: 14,
                                                weight: 'bold'
                                            }
                                        },
                                        tooltip: {
                                            callbacks: {
                                                label: function (context) {
                                                    const label = context.label || '';
                                                    const value = context.raw || 0;
                                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                    const percentage = Math.round((value / total) * 100);
                                                    return `${label}: ${value.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })} (${percentage}%)`;
                                                }
                                            }
                                        }
                                    },

                                    onClick: (evt, elements) => {
                                        if (elements.length > 0) {
                                            const index = elements[0].index;
                                            const subcategory = labels[index]; // 获取点击的子分类名称
                                            console.log('点击了子分类:', subcategory);
                                            // 显示该子分类的账单明细
                                            showBillsModal(null, subcategory);
                                        }
                                    }
                                }
                            });
                        }
                    });

                    // 点击模态框外部关闭
                    const closeModal = () => {
                        modal.remove();
                    };

                    modal.querySelector('.btn-close').addEventListener('click', closeModal);
                    modal.addEventListener('click', (e) => {
                        if (e.target === modal) {
                            closeModal();
                        }
                    });
                };

                // 更新支出饼图配置
                const updateExpenseChart = () => {
                    // ...原有支出饼图配置...
                    options: {
                        // ...其他配置...
                        onClick: (evt, elements) => {
                            if (elements.length > 0) {
                                const index = elements[0].index;
                                const selectedCategory = Object.keys(stats.value.expense_by_category)[index];
                                showSubcategoryModal(selectedCategory);
                            }
                        }
                    }
                };

                // 更新图表
                const updateCharts = () => {
                    // 销毁旧图表实例
                    if (incomeChartInstance) incomeChartInstance.destroy();
                    if (expenseChartInstance) expenseChartInstance.destroy();
                    if (incomeTrendChartInstance) incomeTrendChartInstance.destroy();
                    if (expenseTrendChartInstance) expenseTrendChartInstance.destroy();
                    if (totalIncomeTrendChartInstance) totalIncomeTrendChartInstance.destroy();
                    if (totalExpenseTrendChartInstance) totalExpenseTrendChartInstance.destroy();

                    // 等待DOM更新
                    nextTick(() => {
                        // 收入饼图
                        if (incomeChart.value) {
                            const ctx = incomeChart.value.getContext('2d');
                            incomeChartInstance = new Chart(ctx, {
                                type: 'pie',
                                data: {
                                    labels: Object.entries(stats.value.income_by_subcategory || {})
                                        .sort((a, b) => b[1] - a[1])
                                        .map(item => item[0]),
                                    datasets: [{
                                        data: Object.entries(stats.value.income_by_subcategory || {})
                                            .sort((a, b) => b[1] - a[1])
                                            .map(item => item[1]),
                                        backgroundColor: [
                                            '#4BC0C0', '#36A2EB', '#FFCE56', '#FF6384', '#9966FF',
                                            '#FF9F40', '#8AC24A', '#607D8B', '#E91E63', '#9C27B0'
                                        ]
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        tooltip: {
                                            callbacks: {
                                                label: function (context) {
                                                    const label = context.label || '';
                                                    const value = context.raw || 0;
                                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                    const percentage = Math.round((value / total) * 100);
                                                    return `${label}: ${value.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })} (${percentage}%)`;
                                                }
                                            }
                                        },
                                        title: {
                                            display: true,
                                            text: '总收入: ' + formatCurrency(Object.values(stats.value.income_by_subcategory || {}).reduce((a, b) => a + b, 0)),
                                            position: 'bottom',
                                            font: {
                                                size: 14,
                                                weight: 'bold'
                                            }
                                        }
                                    },


                                    onClick: (evt, elements) => {
                                        if (elements.length > 0) {
                                            const index = elements[0].index;
                                            const sort_data = Object.entries(stats.value.income_by_subcategory || {}).sort((a, b) => b[1] - a[1]);
                                            const category = sort_data[index][0];
                                            // 这里可以添加点击后的交互逻辑
                                            showBillsModal(null, category); // 调用显示账单列表的方法
                                        }
                                    }
                                }
                            });
                        }
                        // 支出饼图
                        if (expenseChart.value) {
                            const ctx = expenseChart.value.getContext('2d');
                            expenseChartInstance = new Chart(ctx, {
                                type: 'pie',
                                data: {
                                    labels: Object.entries(stats.value.expense_by_category || {})
                                        .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))
                                        .map(item => item[0]),
                                    datasets: [{
                                        data: Object.entries(stats.value.expense_by_category || {})
                                            .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))
                                            .map(item => item[1]),
                                        backgroundColor: [
                                            '#4BC0C0', '#36A2EB', '#FFCE56', '#FF6384', '#9966FF',
                                            '#FF9F40', '#8AC24A', '#607D8B', '#E91E63', '#9C27B0'
                                        ]
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    plugins: {
                                        tooltip: {
                                            callbacks: {
                                                label: function (context) {
                                                    const label = context.label || '';
                                                    const value = context.raw || 0;
                                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                    const percentage = Math.round((value / total) * 100);
                                                    return `${label}: ${value.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })} (${percentage}%)`;
                                                }
                                            }
                                        },
                                        title: {
                                            display: true,
                                            text: '总支出: ' + formatCurrency(Object.values(stats.value.expense_by_category || {}).reduce((a, b) => a + b, 0)),
                                            position: 'bottom',
                                            font: {
                                                size: 14,
                                                weight: 'bold'
                                            }
                                        }
                                    },
                                    onClick: (evt, elements) => {
                                        if (elements.length > 0) {
                                            const index = elements[0].index;
                                            const sort_data = Object.entries(stats.value.expense_by_category || {}).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
                                            const category = sort_data[index][0];
                                            console.log('点击了支出分类:', category);
                                            // 这里可以添加点击后的交互逻辑
                                            showSubcategoryModal(category);
                                        }
                                    }
                                }
                            });
                        }
                        // 趋势图（按月/年）
                        if (period.value !== 'day' && stats.value.daily_stats) {
                            // 收入趋势图（按二级分类）
                            if (incomeTrendChart.value) {
                                const ctx = incomeTrendChart.value.getContext('2d');
                                incomeTrendChartInstance = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: stats.value.daily_stats.labels.map(d => period.value === 'month' ? `${d}日` : `${d}月`),
                                        datasets: stats.value.daily_stats.income_datasets.map(dataset => ({
                                            ...dataset,
                                            borderWidth: 2,
                                            pointRadius: 3,
                                            pointHoverRadius: 5
                                        }))
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                title: {
                                                    display: true,
                                                    text: '金额 (元)'
                                                }
                                            },
                                            x: {
                                                title: {
                                                    display: true,
                                                    text: period.value === 'month' ? '日期' : '月份'
                                                }
                                            }
                                        },
                                        plugins: {
                                            title: {
                                                display: true,
                                                text: period.value === 'month' ? '每日收入趋势（按二级分类）' : '每月收入趋势（按二级分类）'
                                            },
                                            legend: {
                                                position: 'right',
                                                labels: {
                                                    font: {
                                                        size: 12,
                                                        family: 'Arial, sans-serif'
                                                    },
                                                    padding: 20,
                                                    boxWidth: 12,
                                                    usePointStyle: true
                                                },
                                                title: {
                                                    display: true,
                                                    text: '分类',
                                                    font: {
                                                        weight: 'bold',
                                                        size: 13
                                                    }
                                                }
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function (context) {
                                                        const label = context.label || '';
                                                        const value = context.raw || 0;
                                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                                        const percentage = Math.round((value / total) * 100);
                                                        return `${label}: ${value.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })} (${percentage}%)`;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                            // 收入趋势图（总收入）
                            if (totalIncomeTrendChart.value) {
                                const ctx = totalIncomeTrendChart.value.getContext('2d');
                                // 计算总支出数据（将所有类别的支出数据相加）
                                const totalIncomeData = [];
                                if (stats.value.daily_stats.income_datasets.length > 0) {
                                    const dataLength = stats.value.daily_stats.income_datasets[0].data.length;
                                    for (let i = 0; i < dataLength; i++) {
                                        let sum = 0;
                                        stats.value.daily_stats.income_datasets.forEach(dataset => {
                                            sum += dataset.data[i];
                                        });
                                        totalIncomeData.push(sum);
                                    }
                                }

                                totalIncomeTrendChartInstance = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: stats.value.daily_stats.labels.map(d => period.value === 'month' ? `${d}日` : `${d}月`),
                                        datasets: [{
                                            label: '总收入',
                                            data: totalIncomeData,
                                            borderColor: '#8AC24A',
                                            backgroundColor: 'rgba(25, 135, 84, 0.2)',
                                            borderWidth: 2,
                                            pointRadius: 3,
                                            pointHoverRadius: 5,
                                            tension: 0.1
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                title: {
                                                    display: true,
                                                    text: '金额 (元)'
                                                }
                                            },
                                            x: {
                                                title: {
                                                    display: true,
                                                    text: period.value === 'month' ? '日期' : '月份'
                                                }
                                            }
                                        },
                                        plugins: {
                                            title: {
                                                display: true,
                                                text: period.value === 'month' ? '每日收入趋势（总金额）' : '每月收入趋势（总金额）'
                                            },
                                            legend: {
                                                position: 'right'
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function (context) {
                                                        return `总收入: ${context.raw.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })}`;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }



                            // 支出趋势图（按类别）
                            if (expenseTrendChart.value) {
                                const ctx = expenseTrendChart.value.getContext('2d');
                                expenseTrendChartInstance = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: stats.value.daily_stats.labels.map(d => period.value === 'month' ? `${d}日` : `${d}月`),
                                        datasets: stats.value.daily_stats.expense_datasets.map(dataset => ({
                                            ...dataset,
                                            borderWidth: 2,
                                            pointRadius: 3,
                                            pointHoverRadius: 5
                                        }))
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                title: {
                                                    display: true,
                                                    text: '金额 (元)'
                                                }
                                            },
                                            x: {
                                                title: {
                                                    display: true,
                                                    text: period.value === 'month' ? '日期' : '月份'
                                                }
                                            }
                                        },
                                        plugins: {
                                            title: {
                                                display: true,
                                                text: period.value === 'month' ? '每日支出趋势（按类别）' : '每月支出趋势（按类别）'
                                            },
                                            legend: {
                                                position: 'right'
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function (context) {
                                                        return `${context.dataset.label}: ${context.raw.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })}`;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                            // 支出趋势图（总金额）
                            if (totalExpenseTrendChart.value) {
                                const ctx = totalExpenseTrendChart.value.getContext('2d');
                                // 计算总支出数据（将所有类别的支出数据相加）
                                const totalExpenseData = [];
                                if (stats.value.daily_stats.expense_datasets.length > 0) {
                                    const dataLength = stats.value.daily_stats.expense_datasets[0].data.length;
                                    for (let i = 0; i < dataLength; i++) {
                                        let sum = 0;
                                        stats.value.daily_stats.expense_datasets.forEach(dataset => {
                                            sum += dataset.data[i];
                                        });
                                        totalExpenseData.push(sum);
                                    }
                                }

                                totalExpenseTrendChartInstance = new Chart(ctx, {
                                    type: 'line',
                                    data: {
                                        labels: stats.value.daily_stats.labels.map(d => period.value === 'month' ? `${d}日` : `${d}月`),
                                        datasets: [{
                                            label: '总支出',
                                            data: totalExpenseData,
                                            borderColor: '#dc3545',
                                            backgroundColor: 'rgba(220, 53, 69, 0.5)',
                                            borderWidth: 2,
                                            pointRadius: 3,
                                            pointHoverRadius: 5,
                                            tension: 0.1
                                        }]
                                    },
                                    options: {
                                        responsive: true,
                                        maintainAspectRatio: false,
                                        scales: {
                                            y: {
                                                beginAtZero: true,
                                                title: {
                                                    display: true,
                                                    text: '金额 (元)'
                                                }
                                            },
                                            x: {
                                                title: {
                                                    display: true,
                                                    text: period.value === 'month' ? '日期' : '月份'
                                                }
                                            }
                                        },
                                        plugins: {
                                            title: {
                                                display: true,
                                                text: period.value === 'month' ? '每日支出趋势（总金额）' : '每月支出趋势（总金额）'
                                            },
                                            legend: {
                                                position: 'right'
                                            },
                                            tooltip: {
                                                callbacks: {
                                                    label: function (context) {
                                                        return `总支出: ${context.raw.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' })}`;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }

                        }
                    });
                };
                // 计算指定分类下的账单列表
                const getBillsByCategory = (category) => {
                    return bills.value.filter(bill => {
                        return bill.category === category;
                    });
                };

                const getBillsBySubcategory = (subcategory) => {
                    return bills.value.filter(bill => {
                        return bill.subcategory === subcategory;
                    });
                };

                // 显示账单列表模态框
                const showBillsModal = (category = null, subcategory = null) => {
                    let categoryBills = [];
                    if (category != null) {
                        categoryBills = getBillsByCategory(category);
                    } else if (subcategory != null) {
                        categoryBills = getBillsBySubcategory(subcategory);
                    }

                    if (categoryBills.length === 0) {
                        alert('该分类下没有账单记录。');
                        return;
                    }
                    const name = category != null ? category : subcategory;

                    // 创建模态框DOM元素
                    const modal = document.createElement('div');
                    modal.className = 'modal fade show';
                    modal.style.display = 'block';
                    modal.innerHTML = `
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">【${name}】账单明细</h5>
                        <button type="button" class="btn-close" onclick="this.parentNode.parentNode.parentNode.remove()"></button>
                    </div>
                    <div class="modal-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>日期</th>
                                        <th>金额</th>
                                        <th>类别</th>
                                        <th>二级分类</th>
                                        <th>账户</th>
                                        <th>备注</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${categoryBills.map(bill => `
                                        <tr>
                                            <td>${bill.date}</td>
                                            <td class="text-success">${formatCurrency(bill.amount)}</td>
                                            <td>${bill.category}</td>
                                            <td>${bill.subcategory || ''}</td>
                                            <td>${bill.account}</td>
                                            <td>${bill.remark || ''}</td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        </div>
                        <div class="text-center mt-3">
                            <h4>总计: ${formatCurrency(
                        categoryBills.reduce((sum, bill) => sum + bill.amount, 0)
                    )}</h4>
                        </div>
                    </div>
                </div>
            </div>
        `;

                    // 添加到body
                    document.body.appendChild(modal);

                    // 点击模态框外部关闭
                    const closeModal = () => {
                        modal.remove();
                    };

                    modal.querySelector('.btn-close').addEventListener('click', closeModal);
                    modal.addEventListener('click', (e) => {
                        if (e.target === modal) {
                            closeModal();
                        }
                    });
                };
                // 初始化
                onMounted(() => {
                    initDates();
                    loadData();

                    // 获取可用的月份和年份
                    const loadMonthsAndYears = async () => {
                        try {
                            const response = await axios.get('/api/bills/months');
                            months.value = response.data;

                            // 从月份数据中提取年份
                            const yearSet = new Set();
                            months.value.forEach(m => yearSet.add(m.split('-')[0]));
                            years.value = Array.from(yearSet).sort((a, b) => b - a);
                        } catch (error) {
                            console.error('加载月份数据失败:', error);
                            // 默认值
                            months.value = [];
                            years.value = [];
                        }
                    };
                    loadMonthsAndYears();
                });

                // 监听period变化
                watch(period, () => {
                    loadData();
                });

                return {
                    incomeChart,
                    expenseChart,
                    incomeTrendChart,
                    expenseTrendChart,
                    totalIncomeTrendChart,
                    totalExpenseTrendChart,
                    period,
                    date,
                    month,
                    year,
                    stats,
                    bills,
                    months,
                    years,
                    loadData,
                    formatCurrency,
                    getBillsByCategory,  // 如果需要外部调用可以返回
                    showBillsModal,     // 如果需要外部调用可以返回
                    expenseTrendType,
                    incomeTrendType,
                    toggleTrend
                };
            }
        }).mount('#app');
    </script>
</body>

</html>